

def exists_query(routes):
    """

    处理请求参数请求参数

    """

    query = {}

    routes = routes.split('?')

    if len(routes) == 1:

        return routes[0], query

    params = routes[1].split('&')

    for param in params:

        value = param.split('=')

        k, v = value[0], value[1]

        query[k.strip()] = v.strip()

    return routes[0], query


def exist_body(rbuff, headers):

    body = {}

    key = 'Content_Length'

    if key not in headers:

        return body

    content_length = int(headers[key])

    data = rbuff.read(content_length)

    params = data.decode().split('&')

    for param in params:

        value = param.split('=')

        k, v = value[0], value[1]

        body[k.strip()] = v.strip()

    return body


def parser_firstline(rbuff):
    """

    处理请求头

    """

    method, routes, http_version = rbuff.readline().decode().strip().split()

    route, query = exists_query(routes)

    return method, route, query, http_version


def parser_header(rbuff):
    """

    处理请求参数

    """

    headers = {}

    while True:

        header = rbuff.readline()

        head = header.decode().split(':')

        if len(head) == 1:

            break

        k, v = head[0], head[1]

        headers[k.strip()] = v.strip()

    return headers


def request_error():
    response = """<!DOCTYPE html>
<html>
    <head> <title>ESP32 Pins</title> </head>
    <body> <h1>ESP32 Pins</h1>
        <table border="1"> <tr><th>Pin</th><th>Value</th></tr> %s </table>
    </body>
</html>"""
    return response


def deal_request(request_params):

    method, route, query, http_version = parser_firstline(request_params)

    print('method:{},route:{},query:{}'.format(method, route, query))

    if method != 'POST':

      return request_error()

    else:
      route = exists_query(route)

      import led

      # light = query.get('light')

      light = [(255, 255, 2)]

      num = int(query.get('num'))

      pin = int(query.get('pin'))

      led.shink_led(pin, num, light)

      response = """HTTP/1.1 200 OK
  Content-Type: text/plain
  Transfer-Encoding: chunked

  25
  This is the data in the first chunk

  1C
  and this is the second one

  3
  con

  8
  sequence

  0"""
      return response
